package com.wunong.smart.address.domain.operation.impl;

import com.wunong.smart.address.client.vo.UserAddressVO;
import com.wunong.smart.address.domain.UserAddressDomain;
import com.wunong.smart.address.application.context.UserAddressContext;
import com.wunong.smart.address.converter.UserAddressDomainConverter;
import com.wunong.smart.address.domain.operation.AbstractUserAddressOperation;
import com.wunong.smart.address.application.request.UpdateUserAddressRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * 添加用户地址
 *
 * @author create by zealot.zt
 */
@Slf4j
@Component
public class UpdateUserAddressOperation extends AbstractUserAddressOperation<UpdateUserAddressRequest> {

    @Override
    protected Object doOperate(UserAddressContext<UpdateUserAddressRequest> context) {
        UpdateUserAddressRequest request = context.getRequest();
        UserAddressDomain domain = context.getDomain();

        if (Objects.nonNull(domain.getId())) {
            userAddressRepository.update(mergeDomain(request, domain));
            log.warn("update user address success, userId:{}, addressId:{}",
                    domain.getUserId(), domain.getId());
            return domain.getId();
        }

        domain = UserAddressDomainConverter.toDomain(request.getAddressVO());
        context.setDomain(domain);
        Long id = userAddressRepository.save(domain);
        log.info("add user address success, userId:{}, addressId:{}", domain.getUserId(), id);
        return id;

    }

    /**
     * 合并领域模型
     *
     * @param request
     * @param oldDomain
     * @return
     */
    protected UserAddressDomain mergeDomain(UpdateUserAddressRequest request, UserAddressDomain oldDomain) {
        UserAddressVO vo = request.getAddressVO();

        oldDomain.setAddressVO(vo);
        oldDomain.setIsDefault(vo.getIsDefault());
        oldDomain.setMobile(vo.getMobile());
        oldDomain.setName(vo.getName());
        oldDomain.setSex(vo.getSex());
        oldDomain.setDescription(vo.getDescription());

        return oldDomain;
    }

    @Override
    public Class<UpdateUserAddressRequest> getRequestClass() {
        return UpdateUserAddressRequest.class;
    }

}
